package mww.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class EncodeFilter implements Filter {	
	private FilterConfig config;
	
	public static final String INIT_PARAM_ENCODE="UTF-8";
	
	public void init(FilterConfig config) throws ServletException{
		this.config=config;
	}
	
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException{
		HttpServletRequest req=(HttpServletRequest)request;
		HttpServletResponse res=(HttpServletResponse)response;
		
		String encode=config.getInitParameter(INIT_PARAM_ENCODE);
		if(encode!=null && !encode.isEmpty()){
			req.setCharacterEncoding(encode);
		}
		
		chain.doFilter(request, response);
		if(encode!=null && !encode.isEmpty()){
			res.setCharacterEncoding(encode);
		}
	}
	
	public void destroy() {
	}
}
